package com.cqie.hospitalescort.controller;

import com.cqie.hospitalescort.entity.IndexCarousel;
import com.cqie.hospitalescort.mapper.IndexCarouselMapper;
import com.cqie.hospitalescort.model.Result;
import com.cqie.hospitalescort.service.file.AliYunService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 主页轮播图 前端控制器
 * </p>
 *
 * @author gdy
 * @since 2025-02-18
 */
@RestController
@RequestMapping("/indexCarousel")
@Api(value = "首页轮播图", tags = {"首页轮播图"})
public class IndexCarouselController extends BaseController {

    @Autowired
    private IndexCarouselMapper indexCarouselMapper;
    @Autowired
    private AliYunService aliYunService;

    @GetMapping("/list")
    @ApiOperation(value = "首页轮播图列表")
    public Result<List<IndexCarousel>> getIndexCarousel() {
        return response(indexCarouselMapper.selectList(null));
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增轮播图")
    @PreAuthorize(value = "hasRole('ROLE_ADMIN')")
    @Transactional
    public Result<List<IndexCarousel>> save(@ModelAttribute IndexCarousel indexCarousel, @RequestParam MultipartFile file) throws IOException {
        //todo 有待完善，暂时不做，直接数据库维护
        List<String> list = aliYunService.uploadFiles(Collections.singletonList(file));
        indexCarousel.setPictureUrl(String.join(",", list));
        indexCarouselMapper.insert(indexCarousel);
        return response();
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除轮播图")
    @PreAuthorize(value = "hasRole('ROLE_ADMIN')")
    @Transactional
    public Result<List<IndexCarousel>> delete(@RequestParam Long id) {
        indexCarouselMapper.deleteById(id);
        return response();
    }

}
